﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Web.Mvc;

namespace MvcControlsToolkit
{
    public class ScriptManager
    {
        internal static readonly string Script_template = "<script language=\"javascript\" type=\"text/javascript\">\r\n{0}</script>\r\n";
        internal static readonly string Script_link_template = "<script src=\"{0}\" type=\"text/javascript\"></script>\r\n";
        internal static readonly string Css_link_template = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />\r\n";

        private static ScriptManager _instance = null;
        private static object _lockKey = new object();

        private Dictionary<string, string> _scriptRefernces = new Dictionary<string, string>();
        private StringBuilder _script = new StringBuilder();

        
        public static void AddReferenceToFile(string script, string type)
        {
            if (!Instance._scriptRefernces.ContainsKey(script))
                Instance._scriptRefernces.Add(script, type);
        }

        public static void InnerScript(string script)
        {
            Instance._script.AppendFormat("{0}\r\n", script);
        }

        public static MvcHtmlString RegistredScripts(string ScriptFolder)
        {
            var result = new StringBuilder();

            foreach(var item in Instance._scriptRefernces.Where(x => x.Value == "script"))
            {
                result.AppendFormat(Script_link_template, ScriptFolder + item.Key);                
            }

            result.AppendFormat(Script_template, Instance._script);

            Instance._script.Clear();

            return MvcHtmlString.Create(result.ToString());
        }

        public static ScriptManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lockKey)
                    {
                        _instance = new ScriptManager();
                    }
                }

                return _instance;
            }
        }

        private ScriptManager() { }
    }
}
